package uutalk.netcloud.talk.app.ui.fragment;

import android.graphics.drawable.AnimationDrawable;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.makeramen.roundedimageview.RoundedImageView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import uutalk.netcloud.talk.R;
import uutalk.netcloud.talk.base.android.BaseFragment;
import uutalk.netcloud.talk.base.mqtt.MQTTManager;
import uutalk.netcloud.talk.base.mqtt.PublishFactory;
import uutalk.netcloud.talk.base.mqtt.event.MqttMessageEvent;
import uutalk.netcloud.talk.base.mqtt.model.Publication;
import uutalk.netcloud.talk.base.util.LanguageUtil;
import uutalk.netcloud.talk.base.util.VibratorUtil;
import uutalk.netcloud.talk.base.util.thirdpart.EventMamager;
import uutalk.netcloud.talk.base.util.thirdpart.ImageLoader;
import uutalk.netcloud.talk.base.util.thirdpart.QiNiuManager;
import uutalk.netcloud.talk.base.util.thirdpart.TalkManager;
import uutalk.netcloud.talk.base.util.thirdpart.UserManager;
import uutalk.netcloud.talk.base.util.view.ToastUtil;
import uutalk.netcloud.talk.model.BussinessBeanFactory;
import uutalk.netcloud.talk.model.bean.CMDConstant;
import uutalk.netcloud.talk.model.bean.DBEntityManager;
import uutalk.netcloud.talk.model.bean.FriendInfoBean;
import uutalk.netcloud.talk.model.bean.JoinSingleTalkRsp;
import uutalk.netcloud.talk.model.bean.SimpleEventType;
import uutalk.netcloud.talk.model.bean.UserInfo;
import uutalk.netcloud.talk.model.bean.UserStatusBean;

/**
 * Created by Administrator on 2018/1/8.
 */

public class SigleTalkFragment extends BaseFragment {

    public final static int TYPE_SEND = 0;
    public final static int TYPE_REC = 1;
    public final static int MSG_TIME_OUT = 998;


    @BindView(R.id.personIcon)
    RoundedImageView personIcon;

    @BindView(R.id.tvName)
    TextView tvName;

    @BindView(R.id.tvTips)
    TextView tvTips;

    @BindView(R.id.llReject)
    LinearLayout llReject;

    @BindView(R.id.tvReject)
    TextView tvReject;

    @BindView(R.id.llAgree)
    LinearLayout llAgree;

    @BindView(R.id.viewSpace)
    View viewSpace;

    @BindView(R.id.ivTalk)
    ImageView ivTalk;

    String groupID;
    private int type;
    JoinSingleTalkRsp joinSingleTalkRsp;
    private String otherUerID;
    UserInfo userInfo = null;
    boolean isTalkConnected;//是否已经建立了聊天连接
    //private static Handler mHandler;

    public static SigleTalkFragment newInstance(String groupID, int type, JoinSingleTalkRsp joinSingleTalkRsp) {
        SigleTalkFragment fragment = new SigleTalkFragment();
        fragment.groupID = groupID;
        fragment.type = type;
        fragment.joinSingleTalkRsp = joinSingleTalkRsp;
        return fragment;
    }

    @Override
    protected int setLayoutResId() {
        return R.layout.fragment_sigle_talk;
    }

    @Override
    public boolean isAutoBindEvent() {
        return true;
    }

    @Override
    public void OnBackPressed(View v) {

    }

    @Override
    protected void loadData() {

    }

    @Override
    protected void init() {
        initViewByType(type);
        setTalkBtnTouchEvent();
        if(joinSingleTalkRsp.getUser_id().equals(UserManager.getInstance().getUserInfo().getUser_id())){
            otherUerID = joinSingleTalkRsp.getReceiver_id();
        } else {
            otherUerID = joinSingleTalkRsp.getUser_id();
        }
        joinSingleTalkRsp.setGroup_id(groupID);
        sendMessageToFragmentDelay(MSG_TIME_OUT, 30000l);

        userInfo = DBEntityManager.getUserInfoById(otherUerID);
        if(userInfo == null){
            FriendInfoBean friendInfoBean = DBEntityManager.getFriendInfoBean(otherUerID);
            if(friendInfoBean != null){
                userInfo = new UserInfo();
                userInfo.setPicture(friendInfoBean.getFriend_picture());
                userInfo.setName(friendInfoBean.getFriend_name());
            }
        }
        if(userInfo == null){
            progressHudUtil.showProgressHud(false);
            Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createGetUserInfoBean(otherUerID));
            MQTTManager.getInstance().publish(publication);
        } else {
            initUserView(userInfo);
        }
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if(msg.what == MSG_TIME_OUT){
            if(isTalkConnected){
                return;
            } else {
                if(type == TYPE_SEND){
                    ToastUtil.makeToast(LanguageUtil.getStringById(R.string.no_response));
                } else {
                    ToastUtil.makeToast(LanguageUtil.getStringById(R.string.str_erro_reject));
                }
                EventMamager.getInstance().postEvent(SimpleEventType.MSG_SIGLE_TALK_FINISH);
                finish();
            }
        }
    }

    @OnClick({R.id.llReject, R.id.llAgree})
    public void onViewClick(View view){
        switch (view.getId()){
            case R.id.llReject:{
                Log.e(TAG, "挂断对话");
                joinSingleTalkRsp.setError_no("2");
                joinSingleTalkRsp.setReceiver_name(userInfo.getName());
                joinSingleTalkRsp.setReceiver_id(userInfo.getUser_id());
                joinSingleTalkRsp.setUser_id(UserManager.getInstance().getUserInfo().getUser_id());
                joinSingleTalkRsp.setUser_name(UserManager.getInstance().getUserInfo().getName());
                requestJoinSingleTalkResp(joinSingleTalkRsp);
                quitTalkChannel();
                finish();
            } break;
            case R.id.llAgree:{
                joinSingleTalkRsp.setError_no("0");
                joinSingleTalkRsp.setReceiver_name(userInfo.getName());
                joinSingleTalkRsp.setReceiver_id(userInfo.getUser_id());
                joinSingleTalkRsp.setUser_id(UserManager.getInstance().getUserInfo().getUser_id());
                joinSingleTalkRsp.setUser_name(UserManager.getInstance().getUserInfo().getName());
                requestJoinSingleTalkResp(joinSingleTalkRsp);
                quitTalkChannel();
                joinTalkChannel(joinSingleTalkRsp.getGroup_id());
                updateViewByStatus(0);
                isTalkConnected = true;
            } break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMqttMsgEvent(MqttMessageEvent event) {
        Log.e(TAG, "请求加入单聊响应>>"+ event.getMessage());
        //收到对方加入单聊响应
        if (CMDConstant.JOIN_SINGLE_TALK_RESP.equals(event.getMessage().getCmd())) {
            progressHudUtil.dismissProgressHud();
            JoinSingleTalkRsp resp = JSON.parseObject(event.getMessage().toString(), JoinSingleTalkRsp.class);
            if(resp.getReceiver_name().equals(UserManager.getInstance().getUserInfo().getName())){
                String singleTalkMemberName = resp.getUser_name();
                onJoinSingleTalkRespCMD(resp);
            }
        }

        if (CMDConstant.JOIN_SINGLE_TALK.equals(event.getMessage().getCmd())) {
            progressHudUtil.dismissProgressHud();
            JoinSingleTalkRsp resp = JSON.parseObject(event.getMessage().toString(), JoinSingleTalkRsp.class);
            if (resp.isOk()) {
                int a = Integer.parseInt(resp.getUser_id());
                int b = Integer.parseInt(resp.getReceiver_id());
                String groupId = "";
                if (a > b) {
                    groupId = b + "_" + a;
                } else {
                    groupId = a + "_" + b;
                }
                resp.setGroup_id(groupId);
                if(!groupId.equals(joinSingleTalkRsp.getGroup_id())){
                    joinSingleTalkRsp.setError_no("3");
                    requestJoinSingleTalkResp(joinSingleTalkRsp);
                }
            }
        }
        //用户状态变化
        if (CMDConstant.USER_STATUS_CHANGED.equals(event.getMessage().getCmd())) {
            UserStatusBean userStatusBean = JSON.parseObject(event.getMessage().toString(), UserStatusBean.class);
            LogUtils.e("用户在线状态变化" + userStatusBean.getStatus() + "-" + userStatusBean.getUser_id());
            if ("0".equals(userStatusBean.getStatus())) {
                if(userStatusBean.getUser_id().equals(otherUerID)){
                    ToastUtil.makeToast(LanguageUtil.getStringById(R.string.str_erro_no_online));
                    TalkManager.getInstance().openMic(false);
                    EventMamager.getInstance().postEvent(SimpleEventType.MSG_SIGLE_TALK_FINISH);
                    finish();
                }
            }
        }

        if (CMDConstant.GET_USER_INFO_RESP_CMD.equals(event.getMessage().getCmd())) {
            //把用户信息保存到本地
            //获取其它用户的信息
            progressHudUtil.dismissProgressHud();
            userInfo = JSON.parseObject(event.getMessage().toString(), UserInfo.class);
            initUserView(userInfo);
        }
    }

    private void initUserView(UserInfo userInfo) {
        ImageLoader.loadImage(mActivity, QiNiuManager.QINIU_HOST+userInfo.getPicture(), personIcon);
        tvName.setText(userInfo.getName());
    }

    private void initViewByType(int type){
        if(type == TYPE_SEND){
            tvTips.setText(getText(R.string.str_req_talk));
            llReject.setVisibility(View.VISIBLE);
            llAgree.setVisibility(View.GONE);
            ivTalk.setVisibility(View.GONE);
            viewSpace.setVisibility(View.GONE);
        } else if(type == TYPE_REC){
            tvTips.setText(getText(R.string.str_rsp_talk ));
            updateViewByStatus(type);
        }
    }

    @Override
    public void gc() {
        super.gc();
    }

    /**
     * 设置说话按点触摸事件
     */
    public void setTalkBtnTouchEvent() {

        ivTalk.setOnTouchListener((View v, MotionEvent event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                onTalkBtnPress(true);
            } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                onTalkBtnPress(false);
            }
            return true;
        });
    }

    /**
     * 是否按住了说话按钮
     *
     * @param isPress
     */
    private void onTalkBtnPress(boolean isPress) {
        if (isPress) {
            if(ivTalk == null){
                return;
            }
            VibratorUtil.Vibrate(mActivity, 100);
            ivTalk.setImageResource(R.drawable.talk_anim);
            AnimationDrawable drawable = (AnimationDrawable) ivTalk.getDrawable();
            drawable.start();
            TalkManager.getInstance().openMic(true);
            LogUtils.e("按下说话");
        } else {
            if(ivTalk == null){
                return;
            }
            TalkManager.getInstance().openMic(false);
            ivTalk.setImageResource(R.drawable.f1);
        }
    }

    private void updateViewByStatus(int status){
        if(status == 0){
            llAgree.setVisibility(View.INVISIBLE);
            ivTalk.setVisibility(View.VISIBLE);
            viewSpace.setVisibility(View.GONE);
            tvTips.setVisibility(View.GONE);
            tvReject.setText(LanguageUtil.getStringById(R.string.str_close_talk));
        } else if(status == 1){
            llAgree.setVisibility(View.VISIBLE);
            ivTalk.setVisibility(View.GONE);
            viewSpace.setVisibility(View.VISIBLE);
        }
    }



    /**
     * 加入单聊响应给对方
     * @param joinSingleTalkRsp
     */
    private void requestJoinSingleTalkResp(JoinSingleTalkRsp joinSingleTalkRsp) {
        if (MQTTManager.getInstance().isConnected()) {
            Log.e(TAG, "加入单聊响应requestJoinSingleTalkResp>>" + joinSingleTalkRsp.getReceiver_name());
            Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createJoinSingleTalkResp(joinSingleTalkRsp));
            MQTTManager.getInstance().publish(publication);
        } else {
            ToastUtil.makeToast(LanguageUtil.getStringById(R.string.get_data_erro));
        }
    }

    /**
     * 退出原来的对讲通道
     */
    private void quitTalkChannel() {
        Log.e(TAG, "退出对讲通道");
        TalkManager.getInstance().leaveChannel();
    }

    /**
     * 加入对讲通道
     */
    private void joinTalkChannel(String groupId) {
        Log.e(TAG, "单人加入对讲"+groupId);
        TalkManager.getInstance().joinChannel(groupId, UserManager.getInstance().getUserInfo().getUser_id());
    }

    /**
     * 发送方收到接收方的回复，请求加入单聊响应
     * @param resp
     */
    private void onJoinSingleTalkRespCMD(JoinSingleTalkRsp resp) {
        Log.e(TAG, "发送方收到接收方的回复，请求加入单聊响应onJoinSingleTalkRespCMD>>" + joinSingleTalkRsp.getGroup_id());
        if (resp.isOk()) {
            quitTalkChannel();
            joinTalkChannel(joinSingleTalkRsp.getGroup_id());
            updateViewByStatus(0);
            isTalkConnected = true;
        } else {
            isTalkConnected = false;
            String iResult = resp.getError_no();
            if("1".equals(iResult)){
                ToastUtil.makeToast(LanguageUtil.getStringById(R.string.str_erro_no_online));
            } else if("2".equals(iResult)){
                ToastUtil.makeToast(LanguageUtil.getStringById(R.string.str_erro_reject));
            } else if("3".equals(iResult)){
                ToastUtil.makeToast(LanguageUtil.getStringById(R.string.str_erro_talking));
            }
            EventMamager.getInstance().postEvent(SimpleEventType.MSG_SIGLE_TALK_FINISH);
            finish();
        }
    }
}
